package com.kinsin.kinsinutils

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.kinsin.kinsinutil.ClickEffectUtil.clickEffect1
import com.kinsin.kinsinutil.ConnectionType
import com.kinsin.kinsinutil.KeyboardUtils
import com.kinsin.kinsinutil.KeyboardUtils.hideKeyboard
import com.kinsin.kinsinutil.Logger
import com.kinsin.kinsinutil.NetworkState
import com.kinsin.kinsinutil.NetworkStateMonitor
import com.kinsin.kinsinutil.SharedPreferenceHelper
import com.kinsin.kinsinutil.TimeUtils
import com.kinsin.kinsinutil.logD
import com.kinsin.kinsinutil.logE
import com.kinsin.kinsinutil.logI
import com.kinsin.kinsinutil.logV
import com.kinsin.kinsinutil.logW
import com.kinsin.kinsinutil.setSafeClickListener
import com.kinsin.kinsinutil.showToast
import com.kinsin.kinsinutil.showToastSafe
import com.kinsin.kinsinutils.databinding.ActivityMainBinding
import kotlin.concurrent.thread

class MainActivity : BaseAppCompatActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        loggerTest()
        testSharedPreference()
        netListener()
    }

    override fun initFirst() {
    }

    override fun initData() {
    }

    private fun netListener() {
        NetworkStateMonitor.getInstance(this@MainActivity).networkState.observe(this) { state ->
            when (state) {
                is NetworkState.ConnectedWithType -> {
                    when (state.type) {
                        ConnectionType.WIFI -> {
                            logD("WIFI now")
                        }
                        ConnectionType.CELLULAR -> {
                            logD("Cellular now")
                        }
                        else -> {
                            logD("UnKnow state")
                        }
                    }
                }
                NetworkState.Disconnected -> {
                    logD("Disconnect")
                }
                else -> {}
            }
        }
    }

    override fun initAction() {
        // region 测试点击效果
        /* clickEffect1使用方法一 */
        binding.testBtn1.clickEffect1(10f).also {
            it.setOnClickListener {
                Toast.makeText(this, "click", Toast.LENGTH_SHORT).show()
            }
            it.setOnLongClickListener {
                Toast.makeText(this, "long click", Toast.LENGTH_SHORT).show()
                false
            }
        }

        /* clickEffect1使用方法二 */
        binding.testBtn2.clickEffect1(20f).apply {
            setOnClickListener {
                Toast.makeText(this@MainActivity, "click", Toast.LENGTH_SHORT).show()
            }
            setOnLongClickListener {
                Toast.makeText(this@MainActivity, "long click", Toast.LENGTH_SHORT).show()
                false
            }
        }
        // endregion 测试点击效果

        // region Toast测试按钮
        binding.testBtn3.setOnClickListener {
            testToastMain()
        }
        binding.testBtn4.setOnClickListener {
            testToastThread()
        }
        binding.testBtn5.setOnClickListener {
            testToastRepeat()
        }
        binding.testBtn6.setOnClickListener {
            testToastNullSafe()
        }
        // endregion Toast测试按钮

        // 防抖动点击测试
        binding.testBtn7.setSafeClickListener {
            showToast("点击了按钮 ${TimeUtils.getCurrentFormattedTime()}")

        }
        binding.testBtn8.setSafeClickListener(interval = 500, preCheck = {
            showToast("前置检查")
            true
        }, onQuickClick = {
            showToast("请勿快速点击")
        }, {
            // 使用split将本按钮文字解析为数组,将第二位的数字提取出来,自增后重新放回去
            var arr = binding.testBtn8.text.toString().split(",")
            val num = arr[1].toInt() + 1
            binding.testBtn8.text = "防抖动点击,$num"
        })

        binding.testBtn9.setOnClickListener {
            if (KeyboardUtils.isKeyboardVisible(this)) {
                logD("当前软键盘存在")
                hideKeyboard(this)
            } else {
                logD("当前软键盘不存在")
                KeyboardUtils.showKeyboard(it, 100)
            }
        }
    }

    // region 测试共享参数
    private fun testSharedPreference() {
        // 使用默认文件名
        val defaultHelper = SharedPreferenceHelper.getInstance(this)
        defaultHelper.put("highScore", 1000)

        // 使用自定义文件名
        val customHelper = SharedPreferenceHelper.getInstance(this, "UserSettings")
        customHelper.put("userName", "John")

        // 类型安全的读取
        val score: Int = defaultHelper.get("highScore", 0)
        val name: String = customHelper.get("userName", "Guest")
        logD("MainShared","读取结果：分数=$score, 姓名=$name")
    }
    // endregion 测试共享参数

    // region 测试Logger
    private fun loggerTest() {
        // 测试配置 ================================
        Logger.isEnabled = true
        Logger.showThreadInfo = true
        Logger.showClassInfo = true
        Logger.tagPrefix = "App"
        Logger.maxLogLength = 40

        // 测试用例 ================================
        testBasicLogging()
        testTagGeneration()
        testMessageChunking()
        testExceptionLogging()
        testPerformance()
        testSpecialCases()
        testConfigurationSwitches()
    }

    private fun testBasicLogging() {
        Log.d("LoggerTest/基本功能", "==== 开始基础日志测试 ====")
        logV("Verbose级别日志")
        logD("Debug级别日志")
        logI("Info级别日志")
        logW("Warn级别日志")
        logE("Error级别日志")
    }

    private fun testTagGeneration() {
        Log.d("LoggerTest/标签生成", "==== 开始标签生成测试 ====")
        // 自动标签
        logD("自动生成的TAG应显示当前类名")
        // 手动标签
        logD("ManualTag", "手动指定的TAG应生效")
    }

    private fun testMessageChunking() {
        Log.d("LoggerTest/消息分块", "==== 开始分块测试 ====")
        val longMsg = "这是一条非常长的日志消息-" +
                "0".repeat(100) +
                "END"
        logD(longMsg)
    }

    private fun testExceptionLogging() {
        Log.d("LoggerTest/异常处理", "==== 开始异常测试 ====")
        try {
            throw RuntimeException("测试异常")
        } catch (e: Exception) {
            logE("捕获到异常", e)
        }
    }

    private fun testPerformance() {
        Log.d("LoggerTest/性能测试", "==== 开始性能测试 ====")
        // 高频日志测试
        val startTime = System.currentTimeMillis()
        repeat(100) {
            logD("性能测试消息 $it")
        }
        Log.d("LoggerTest/性能测试",
            "耗时：${System.currentTimeMillis() - startTime}ms")
    }

    private fun testSpecialCases() {
        Log.d("LoggerTest/特殊场景", "==== 开始特殊场景测试 ====")
        // 空消息
        logD("")
        // 特殊字符
        logD("换行符测试：第一行\n第二行")
        logD("Unicode测试：中文测试 🚀😀")
        // 线程测试
        thread {
            logD("子线程日志")
        }
    }

    private fun testConfigurationSwitches() {
        Log.d("LoggerTest/配置开关", "==== 开始配置测试 ====")
        // 禁用日志
        Logger.isEnabled = false
        logD("这行日志不应该出现")
        // 恢复配置
        Logger.isEnabled = true
        Logger.showClassInfo = false
        logD("类信息已关闭的日志")
    }
    // endregion

    // region Toast测试
    /**
     * 场景1：主线程直接显示
     */
    private fun testToastMain() {
        showToast("主线程正常 Toast")
    }

    /**
     * 场景2：子线程安全显示
     */
    private fun testToastThread() {
        thread(name = "background-thread") {
            showToastSafe("子线程安全 Toast (来自后台线程)")
        }
    }

    /**
     * 场景3：快速连续调用（验证取消逻辑）
     */
    private fun testToastRepeat() {
        repeat(3) { index ->
            showToast("快速连续 Toast $index")
        }
    }

    /**
     * 场景4：空上下文调用（验证空安全）
     */
    private fun testToastNullSafe() {
        val nullContext: Context? = null
        nullContext.showToastSafe("不应崩溃的 Toast")
    }
    // endregion Toast测试

}